<template>
  <div class="announcement-container">
    <el-card class="announcement-card">
      <template #header>
        <div class="card-header">
          <h3>公告通知</h3>
          <el-button 
            v-if="role === '宿管'" 
            type="primary" 
            @click="showAddDialog" 
            size="small"
          >
            发布公告
          </el-button>
        </div>
      </template>
      
      <!-- 搜索过滤 -->
      <div class="filter-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="标题">
            <el-input v-model="searchForm.biaoti" placeholder="请输入标题关键词" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 公告列表 -->
      <div class="announcement-list">
        <el-table
          v-loading="loading"
          :data="announcementList"
          style="width: 100%"
          @row-click="handleRowClick"
        >
          <el-table-column prop="biaoti" label="标题" min-width="180">
            <template #default="scope">
              <div class="announcement-title">
                <span class="title-text">{{ scope.row.biaoti }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="suguanxingming" label="发布人" width="120"></el-table-column>
          
          <el-table-column prop="loudong" label="对应楼栋" width="120"></el-table-column>
          <el-table-column prop="gonggaoleixing" label="公告类型" width="120"></el-table-column>
          <el-table-column prop="fabushijian" label="发布时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.fabushijian) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click.stop="viewDetail(scope.row)">查看</el-button>
              <el-button 
                v-if="role === '宿管'" 
                size="small" 
                type="danger" 
                @click.stop="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="limit"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>
    
    <!-- 公告详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailTitle"
      width="60%"
      destroy-on-close
    >
      <div class="announcement-detail">
        <div class="detail-header">
          <div class="detail-info">
            <span class="publisher">发布人: {{ currentDetail.suguanxingming }}</span>
             <span class="publisher">对应楼栋: {{ currentDetail.loudong }}</span>
              <span class="publisher">公告类型: {{ currentDetail.gonggaoleixing }}</span>
            <span class="publish-time">发布时间: {{ formatDate(currentDetail.fabushijian) }}</span>
          </div>
        </div>
        <div class="detail-content" v-if="currentDetail.tupian">
          <img :src="getFileUrl(currentDetail.tupian)" class="detail-image" alt="公告图片">
        </div>
        <div class="detail-text">
          <p v-html="currentDetail.neirong"></p>
        </div>
      </div>
    </el-dialog>
    
    <!-- 添加公告对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="发布公告"
      width="60%"
      destroy-on-close
    >
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="100px">
        <el-form-item label="标题" prop="biaoti">
          <el-input v-model="addForm.biaoti" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item label="楼栋" prop="loudong">
          <el-input v-model="addForm.loudong" placeholder="请输入公告对应的楼栋"></el-input>
        </el-form-item>

        <el-form-item label="公告类型" prop="gonggaoleixing">
          <el-select 
            v-model="addForm.gonggaoleixing" 
            placeholder="请选择公告类型"
            clearable
            filterable
          >
            <el-option
              value="违规"
              label="违规"
            />
            <el-option
              value="通知"
              label="通知"
            />
            <el-option
              value="其他"
              label="其他"
            />
          </el-select>
        </el-form-item>


        <el-form-item label="封面图片">
          <el-upload
            class="upload-demo"
            action=""
            :http-request="uploadImage"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="addForm.tupian" :src="getFileUrl(addForm.tupian)" class="avatar">
            <el-button v-else type="primary">点击上传</el-button>
            <div class="el-upload__tip">
              建议上传图片比例为16:9，JPG/PNG格式，不超过5MB
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="内容" prop="neirong">
          <el-input
            v-model="addForm.neirong"
            type="textarea"
            :rows="10"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { announcementAPI, fileAPI } from '@/utils/api'

// 角色判断
const role = computed(() => localStorage.getItem('role') || '')

// 数据列表
const announcementList = ref([])
const loading = ref(false)
const total = ref(0)
const page = ref(1)
const limit = ref(10)

// 搜索表单
const searchForm = reactive({
  biaoti: '',
  loudong:localStorage.getItem('loudong')
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})
const detailTitle = computed(() => currentDetail.value.biaoti || '公告详情')

// 添加对话框
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  biaoti: '',
  tupian: '',
  neirong: '',
  suguanzhanghao: localStorage.getItem('adminName') || '',//发送的是账号而不是姓名，登录的时候没有姓名
  suguanxingming: localStorage.getItem('adminName') || ''
})

// 表单验证规则
const rules = {
  biaoti: [{ required: true, message: '请输入公告标题', trigger: 'blur' }],
  neirong: [{ required: true, message: '请输入公告内容', trigger: 'blur' }],
  loudong: [{ required: true, message: '请输入公告对应的楼栋', trigger: 'blur' }],
  gonggaoleixing: [{ required: true, message: '请输入选择公告类型', trigger: 'blur' }],
}

// 初始化加载数据
onMounted(() => {
  getAnnouncementList()
})

// 获取公告列表
const getAnnouncementList = async () => {
  loading.value = true
  try {
    const params = {
      page: page.value,
      limit: limit.value,
      ...searchForm
    }
    
    const res = await announcementAPI.getPage(params)
    if (res.code === 0) {
      announcementList.value = res.data.list
      total.value = res.data.total
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleSearch = () => {
  page.value = 1
  getAnnouncementList()
}

// 重置查询
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页事件处理
const handleSizeChange = (val) => {
  limit.value = val
  getAnnouncementList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getAnnouncementList()
}

// 行点击事件
const handleRowClick = (row) => {
  viewDetail(row)
}

// 查看详情
const viewDetail = async (row) => {
  try {
    const res = await announcementAPI.getDetail(row.id)
    if (res.code === 0) {
      currentDetail.value = res.data
      detailDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取公告详情失败:', error)
  }
}

// 删除公告
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await announcementAPI.delete([row.id])
      if (res.code === 0) {
        ElMessage.success('删除成功')
        getAnnouncementList()
      }
    } catch (error) {
      console.error('删除公告失败:', error)
    }
  }).catch(() => {})
}

// 显示添加对话框
const showAddDialog = () => {
  Object.keys(addForm).forEach(key => {
    if (!['suguanzhanghao', 'suguanxingming'].includes(key)) {
      addForm[key] = ''
    }
  })
  addDialogVisible.value = true
}

// 上传图片前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('上传图片大小不能超过 5MB!')
    return false
  }
  return true
}

// 上传图片
const uploadImage = async (params) => {
  try {
    const res = await fileAPI.upload(params.file)
    if (res.code === 0) {
      addForm.tupian = res.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
  }
}

// 提交表单
const submitForm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const now = new Date()
        const data = {
          ...addForm,
          fabushijian: now
        }
        
        const res = await announcementAPI.add(data)
        if (res.code === 0) {
          ElMessage.success('发布公告成功')
          addDialogVisible.value = false
          getAnnouncementList()
        }
      } catch (error) {
        console.error('发布公告失败:', error)
      }
    }
  })
}

// 获取文件URL
const getFileUrl = (fileName) => {
  if (!fileName) return ''
  return fileAPI.getFileUrl(fileName)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  if (typeof date === 'string') {
    return date
  }
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hour = String(d.getHours()).padStart(2, '0')
  const minute = String(d.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}`
}
</script>

<style lang="scss" scoped>
.announcement-container {
  padding: 20px;
  
  .announcement-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        margin: 0;
      }
    }
    
    .filter-container {
      margin-bottom: 20px;
    }
    
    .announcement-list {
      .announcement-title {
        display: flex;
        align-items: center;
        
        .title-text {
          font-weight: 500;
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
  
  .announcement-detail {
    .detail-header {
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
      
      .detail-info {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        color: #666;
        font-size: 14px;
      }
    }
    
    .detail-content {
      margin-bottom: 20px;
      
      .detail-image {
        max-width: 100%;
        border-radius: 4px;
      }
    }
    
    .detail-text {
      line-height: 1.8;
    }
  }
  
  .avatar {
    width: 178px;
    height: 100px;
    object-fit: cover;
    border-radius: 4px;
  }
}
</style> 